package org.hj.modules.act.leave.controller;

import java.util.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.util.Excel.ExportParams;
import org.hj.common.system.util.Excel.HjEntityExcelView;
import org.hj.common.system.util.Excel.NormalExcelConstants;
import org.hj.common.system.vo.LoginUser;
import org.hj.common.util.oConvertUtils;

import org.hj.modules.AcStartController;
import org.hj.modules.act.leave.entity.OaLeaveBill;
import org.hj.modules.act.leave.service.IOaLeaveBillService;
import org.hj.modules.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: assas
 * @Author: gaobw
 * @Date:   2020-05-13
 * @Version: V1.0
 */
@Slf4j
@Api(tags="leave")
@RestController
@RequestMapping("/leave/oaLeaveBill")
public class OaLeaveBillController  extends AcStartController {
	@Autowired
	private IOaLeaveBillService oaLeaveBillService;
	
	/**
	  * 分页列表查询
	 * @param oaLeaveBill
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "assas-分页列表查询")
	@ApiOperation(value="assas-分页列表查询", notes="assas-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<OaLeaveBill>> queryPageList(OaLeaveBill oaLeaveBill,
													@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													HttpServletRequest req) {
		Result<IPage<OaLeaveBill>> result = new Result<IPage<OaLeaveBill>>();
		QueryWrapper<OaLeaveBill> queryWrapper = QueryGenerator.initQueryWrapper(oaLeaveBill, req.getParameterMap());
		Page<OaLeaveBill> page = new Page<OaLeaveBill>(pageNo, pageSize);
		IPage<OaLeaveBill> pageList = oaLeaveBillService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param oaLeaveBill
	 * @return
	 */
//	@AutoLog(value = "assas-添加")
//	@ApiOperation(value="assas-添加", notes="assas-添加")
//	@PostMapping(value = "/add")
//	public Result<OaLeaveBill> add(@RequestBody OaLeaveBill oaLeaveBill) {
//		Result<OaLeaveBill> result = new Result<OaLeaveBill>();
//		try {
//			oaLeaveBillService.save(oaLeaveBill);
//			result.success("添加成功！");
//		} catch (Exception e) {
//			log.error(e.getMessage(),e);
//			result.error500("操作失败");
//		}
//		return result;
//	}

	 /**保存请假单
	  * @param
	  * @throws Exception
	  */
	 @RequestMapping(value="/add")
	 @ResponseBody
	 public Object add(@RequestBody OaLeaveBill oaLeaveBill){

		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();


		 Map<String,Object> zmap = new HashMap<String,Object>();
		 String errInfo = "success";
		 oaLeaveBill.setUsername(sysUser.getUsername());			//用户名
		 try {
			 /** 工作流的操作 **/
			 Map<String,Object> map = new LinkedHashMap<String, Object>();
			 map.put("请假人员", sysUser.getUsername());			//当前用户的姓名
			 map.put("开始时间", oaLeaveBill.getStartTime());
			 map.put("结束时间", oaLeaveBill.getEndTime());
			 map.put("请假时长", oaLeaveBill.getDays());
			 map.put("请假类型", oaLeaveBill.getType());
			 map.put("请假事由", oaLeaveBill.getReason());
			 map.put("username", sysUser.getUsername());			//指派代理人为当前用户
			 startProcessInstanceByKeyHasVariables("A11",map);		//启动流程实例(请假单流程)通过KEY
			 oaLeaveBillService.save(oaLeaveBill);									//记录存入数据库
			 zmap.put("ASSIGNEE_",sysUser.getUsername());			//用于给待办人发送新任务消息
		 } catch (Exception e) {
			 errInfo = "errer";
		 }
		 zmap.put("result", errInfo);				//返回结果
		 return zmap;
	 }




	 /**
	  *  编辑
	 * @param oaLeaveBill
	 * @return
	 */
	@AutoLog(value = "编辑")
	@ApiOperation(value="assas-编辑", notes="assas-编辑")
	@PutMapping(value = "/edit")
	public Result<OaLeaveBill> edit(@RequestBody OaLeaveBill oaLeaveBill) {
		Result<OaLeaveBill> result = new Result<OaLeaveBill>();
		OaLeaveBill oaLeaveBillEntity = oaLeaveBillService.getById(oaLeaveBill.getLeaveId());
		if(oaLeaveBillEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = oaLeaveBillService.updateById(oaLeaveBill);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "assas-通过id删除")
	@ApiOperation(value="assas-通过id删除", notes="assas-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<OaLeaveBill> delete(@RequestParam(name="id",required=true) String id) {
		Result<OaLeaveBill> result = new Result<OaLeaveBill>();
		OaLeaveBill oaLeaveBill = oaLeaveBillService.getById(id);
		if(oaLeaveBill==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = oaLeaveBillService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "assas-批量删除")
	@ApiOperation(value="assas-批量删除", notes="assas-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<OaLeaveBill> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<OaLeaveBill> result = new Result<OaLeaveBill>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.oaLeaveBillService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "assas-通过id查询")
	@ApiOperation(value="assas-通过id查询", notes="assas-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<OaLeaveBill> queryById(@RequestParam(name="id",required=true) String id) {
		Result<OaLeaveBill> result = new Result<OaLeaveBill>();
		OaLeaveBill oaLeaveBill = oaLeaveBillService.getById(id);
		if(oaLeaveBill==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(oaLeaveBill);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<OaLeaveBill> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              OaLeaveBill oaLeaveBill = JSON.parseObject(deString, OaLeaveBill.class);
              queryWrapper = QueryGenerator.initQueryWrapper(oaLeaveBill, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new HjEntityExcelView());
      List<OaLeaveBill> pageList = oaLeaveBillService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "assas列表");
      mv.addObject(NormalExcelConstants.CLASS, OaLeaveBill.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("assas列表数据", "导出人:cg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
/*  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<OaLeaveBill> listOaLeaveBills = ExcelImportUtil.importExcel(file.getInputStream(), OaLeaveBill.class, params);
              for (OaLeaveBill oaLeaveBillExcel : listOaLeaveBills) {
                  oaLeaveBillService.save(oaLeaveBillExcel);
              }
              return Result.ok("文件导入成功！数据行数:" + listOaLeaveBills.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }*/

}
